<template>
  <div class="sign">
    <el-dialog
      v-model="signVisible"
      title="注册帐号"
      width="500"
      draggable
      :before-close="cancelSign"
    >
      <!-- 步骤条 -->
      <el-steps style="max-width: 600px" :active="active" finish-status="success">
        <el-step title="帐号信息" />
        <el-step title="其他信息" />
        <el-step title="密保问题" />
        <el-step title="邮箱验证" />
      </el-steps>
      <div style="width: 100%; height: 30px"></div>
      <!-- 帐号信息 -->
      <el-form
        v-show="active == 0"
        label-width="auto"
        :model="accountSign"
        style="width: 350px"
        ref="formAccount"
        :rules="rules"
      >
        <el-form-item label="帐号" prop="id">
          <el-input v-model="accountSign.id" placeholder="请输入你的帐号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="accountSign.password"
            type="password"
            show-password
            placeholder="请输入你的密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="rePassword">
          <el-input
            v-model="accountSign.rePassword"
            type="password"
            show-password
            placeholder="确认你的密码"
          />
        </el-form-item>
      </el-form>
      <!-- 更多信息 -->
      <el-form
        v-show="active == 1"
        label-width="auto"
        :model="accountSign"
        style="width: 350px"
        ref="formInfo"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="accountSign.name" placeholder="请输入你的用户名" />
        </el-form-item>
        <el-form-item style="margin-left: 10px">
          <span class="demonstration">性别 &nbsp;</span>
          <el-radio v-model="accountSign.gender" value="true">男</el-radio>
          <el-radio v-model="accountSign.gender" value="false">女</el-radio>
        </el-form-item>
        <el-form-item style="margin-left: 10px">
          <span class="demonstration">出生日期&nbsp;</span>
          <el-date-picker v-model="accountSign.birthday" type="date" placeholder="出生日期" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="accountSign.phone" placeholder="请输入你的电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="accountSign.address" placeholder="请输入你的住址" />
        </el-form-item>
      </el-form>
      <!-- 密保问题 -->
      <el-form
        v-show="active == 2"
        label-width="auto"
        :model="accountSign"
        style="width: 350px"
        ref="formAnswer"
        :rules="rules"
      >
        <el-form-item label="问题1" prop="question1">
          <el-input v-model="accountSign.question1" placeholder="请输入第一个问题" />
        </el-form-item>
        <el-form-item label="答案1" prop="answer1">
          <el-input v-model="accountSign.answer1" placeholder="请输入第一个问题的答案" />
        </el-form-item>
        <el-form-item label="问题2" prop="question2">
          <el-input v-model="accountSign.question2" placeholder="请输入第二个问题" />
        </el-form-item>
        <el-form-item label="答案2" prop="answer2">
          <el-input v-model="accountSign.answer2" placeholder="请输入第二个问题的答案" />
        </el-form-item>
      </el-form>
      <!--短信验证-->
      <el-form v-show="active == 3" :model="accountSign" label-width="auto" style="width: 350px">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="accountSign.email" placeholder="请输入你的邮箱" style="width: 250px" />
          <el-button
            type="success"
            class="verification-code"
            @click="startCountdown"
            :disabled="!isCheckVerificationCode"
          >
            {{ isCheckVerificationCode ? '发送验证码' : countdown + 's后可重新发送' }}
          </el-button>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="verificationCode" placeholder="请输入验证码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelSign">取消</el-button>
          <el-button type="primary" @click="nextOrSure">
            {{ active < 3 ? '下一步' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { sign } from '@/api/login'
import { saveAnswer, saveUser } from '@/api/user'
import { getVerificationCode, verifyVerificationCode } from '@/api/login'
import { startLoading, stopLoading } from '@/utils/loading'
import { ref, onUnmounted } from 'vue'
import { ElNotification } from 'element-plus'

const signVisible = ref(true)

const emit = defineEmits(['close'])

// 正则校验
const regex = {
  emailRegex:
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
  addressRegex: /^[^\r\n]{1,40}$/,
  phoneRegex: /^\+?[1-9]\d{1,14}(\(\d{1,3}\)|\s?\d{1,3})?[-.\s]?\d{1,14}$/,
  answerRegex: /^[^\r\n]{1,30}$/,
}

// 表单校验
const rules = {
  id: [
    { required: true, message: '请输入帐号', trigger: 'blur' },
    { min: 6, max: 15, message: '帐号必须是6-15位字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur',
    },
  ],
  rePassword: [
    { required: true, message: '请重复输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value !== accountSign.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 20, message: '用户名必须是1-20位字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: regex.emailRegex,
      message: '请按照正确的格式输入邮箱',
      trigger: 'blur',
    },
  ],
  phone: [
    { required: true, message: '请输入正确的手机号', trigger: 'blur' },
    {
      pattern: regex.phoneRegex,
      message: '请按照正确的格式输入手机号',
      trigger: 'blur',
    },
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    {
      pattern: regex.addressRegex,
      message: '不能超过40个字符',
      trigger: 'blur',
    },
  ],
  answer1: [
    { required: true, message: '请输入第一个问题的答案', trigger: 'blur' },
    {
      pattern: regex.answerRegex,
      message: '不能超过30个字符',
      trigger: 'blur',
    },
  ],
  answer2: [
    { required: true, message: '请输入第二个问题的答案', trigger: 'blur' },
    {
      pattern: regex.answerRegex,
      message: '不能超过30个字符',
      trigger: 'blur',
    },
  ],
  question1: [
    { required: true, message: '请输入第一个问题', trigger: 'blur' },
    {
      pattern: regex.answerRegex,
      message: '不能超过30个字符',
      trigger: 'blur',
    },
  ],
  question2: [
    { required: true, message: '请输入第二个问题', trigger: 'blur' },
    {
      pattern: regex.answerRegex,
      message: '不能超过30个字符',
      trigger: 'blur',
    },
  ],
}

// 账号信息
const accountSign = ref({
  id: '',
  password: '',
  rePassword: '',
  name: '',
  email: '',
  gender: 'true',
  birthday: '',
  phone: '',
  address: '',
  question1: '',
  answer1: '',
  question2: '',
  answer2: '',
})

// 验证码
const verificationCode = ref('')

// 是否可以点击发送验证码
const isCheckVerificationCode = ref(true)

// 步骤条
const active = ref(0)

// 帐号表单ref对象
const formAccount = ref()

// 其他信息表单ref对象
const formInfo = ref()

// 密保问题表单ref对象
const formAnswer = ref()

// 下一步/确定
const nextOrSure = async () => {
  if (active.value < 1) {
    await formAccount.value.validate()
    active.value++
  } else if (active.value < 2) {
    await formInfo.value.validate()
    active.value++
  } else if (active.value < 3) {
    active.value++
  } else {
    console.log(formAnswer.value)
    // 校验表单
    await formAnswer.value.validate()
    // 校验验证码
    const isCorrect = await verifyVerificationCode(accountSign.value.email, verificationCode.value)
    // 判断验证码是否正确
    if (!isCorrect.data.success) {
      ElNotification({
        title: '注册失败',
        message: '验证码错误',
        type: 'error',
      })
      return
    }
    // 注册账号
    const res = await sign({ id: accountSign.value.id, password: accountSign.value.password })
    if (res.data.success) {
      //开始加载
      startLoading()
      // 保存用户信息
      await saveUser({ ...accountSign.value })
      // 保存密保问题
      await saveAnswer({
        id: accountSign.value.id,
        questions: {
          [accountSign.value.question1]: accountSign.value.answer1,
          [accountSign.value.question2]: accountSign.value.answer2,
        },
      })
      //取消加载
      stopLoading()
      // 关闭弹窗
      cancelSign()
      //注册成功
      ElNotification({
        title: '注册成功',
        message: '你已成功注册账号',
        type: 'success',
      })
    } else {
      ElNotification({
        title: '注册失败',
        message: `${res.data.errorMsg}`,
        type: 'error',
      })
    }
  }
}

//六十秒倒计时
const countdown = ref(60)

//时间控制器
let timer = null

//开始倒数
const startCountdown = async () => {
  const email = accountSign.value.email
  if (email == null || email === '') {
    //邮箱不能为空
    ElNotification({
      title: '获取验证码失败',
      message: '邮箱不能为空',
      type: 'error',
    })
    return
  }
  // 禁止反复点击
  isCheckVerificationCode.value = false
  // 发送验证码
  await getVerificationCodeFun()
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      // 重置倒计时
      countdown.value = 60
      // 允许重新发送
      isCheckVerificationCode.value = true
      //清除时间对象
      clearInterval(timer)
    }
  }, 1000)
}

// 发送验证码
const getVerificationCodeFun = async () => {
  const email = accountSign.value.email
  await getVerificationCode(email)
}

// 取消注册
const cancelSign = () => {
  accountSign.value = {
    username: '',
    password: '',
    rePassword: '',
    name: '',
    email: '',
    gender: 'true',
    birthday: '',
    phone: '',
    address: '',
    question1: '',
    answer1: '',
    question2: '',
    answer2: '',
  }
  emit('close')
}

//清除时间对象
onUnmounted(() => {
  isCheckVerificationCode.value = true
  clearInterval(timer)
})
</script>

<style scoped less="scss">
.sign {
  /*脱离flex布局*/
  position: absolute;

  width: 600px;
  height: 500px;
  z-index: 1;

  .tips {
    position: relative;
    left: 15%;

    margin-bottom: 10px;
  }

  .verification-code {
    position: relative;
    left: 88%;
    bottom: 50%;
  }
}
</style>
